<script setup lang="ts">
import type { PositionSchema } from "@/types/account.types";
import { usePositionAnalyzing } from "@/composables/useAccountTable/usePositionAnalyzing";
import { usePositionAnalysis } from "./PositionAnalysis";
import { ArrowDown, ArrowUp } from "@element-plus/icons-vue";
defineOptions({
  name: "position-analysis"
});

const props = withDefaults(
  defineProps<{
    position: PositionSchema[];
    height?: string | null;
    size?: "small" | "default" | "large";
    title?: string;
    compact?: boolean;
  }>(),
  {
    height: null,
    size: undefined,
    title: undefined,
    compact: false
  }
);

const { analyzePosition, isFilterOnlyFutures } = usePositionAnalyzing();
const {
  tableSize,
  expandRowKeys,
  handleExpandChange,
  positionAnalysisColumns,
  expandAll,
  collapseAll
} = usePositionAnalysis(props.compact);
</script>

<template>
  <div
    :class="[
      props.height ? 'flex h-full flex-col' : '',
      props.compact ? 'compact-mode' : ''
    ]"
  >
    <div
      :class="[
        'flex items-center gap-2 px-1',
        props.compact ? 'my-1' : 'my-1 sm:my-2 md:my-3'
      ]"
    >
      <span v-if="props.title" class="text-sm font-medium text-gray-700">{{
        props.title
      }}</span>
      <div class="flex-c gap-1">
        <el-button
          class="m-0!"
          type="default"
          size="small"
          :icon="ArrowDown"
          @click="expandAll(analyzePosition(position))"
        >
          <span v-if="!props.compact" class="m-0! max-sm:hidden!">展</span
          ><span>开</span>
        </el-button>

        <el-button
          class="m-0!"
          type="default"
          size="small"
          :icon="ArrowUp"
          @click="collapseAll"
        >
          <span>收</span
          ><span v-if="!props.compact" class="m-0! max-sm:hidden!">起</span>
        </el-button>
      </div>
      <el-switch v-model="isFilterOnlyFutures" :size="tableSize" />
      <span
        :class="
          props.compact
            ? 'text-xs text-gray-500'
            : 'text-xs text-gray-500 sm:text-sm'
        "
      >
        过滤只有期货的行
      </span>
    </div>
    <div :class="props.height ? 'min-h-0 flex-1 overflow-hidden' : ''">
      <pure-table
        :data="analyzePosition(position)"
        :columns="positionAnalysisColumns"
        :row-key="
          row => `${row.underlying_symbol}-${row.symbol}-${row.direction}`
        "
        :row-class-name="
          params => (params.row.is_summary_row ? 'bg-gray-100!' : '')
        "
        :expand-row-keys="expandRowKeys"
        :size="props.size ?? tableSize"
        :height="props.height"
        @expand-change="handleExpandChange"
      />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.compact-mode :deep(.el-table--small .cell) {
  padding: 0 4px;
}

@media screen and (width <= 768px) {
  :deep(.el-table--small .cell) {
    padding: 0 4px;
  }
}
</style>
